/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.maslyk.invitation.page;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import com.maslyk.invitation.exception.LogicalException;

/**
 *
 * @author kris
 */
public class Utils
{

    public static String encodeString(String str)
    {
        if (str == null)
            return null;
        StringBuilder buf = new StringBuilder();
        int n = str.length();
        for (int i = 0; i < n; i++)
        {
            char ch = str.charAt(i);
            switch (ch)
            {
                case '\n':
                    buf.append("<br>");
                    break;
                default:
                    buf.append(ch);
            }
        }
        return buf.toString();
    }

    public static String getFileContent(String fileName) throws LogicalException, IOException
    {
        ClassLoader cl = Utils.class.getClassLoader();
        URL url = cl.getResource(fileName);
        if (url == null)
            throw new LogicalException("File '" + fileName + "' is missing.");

        return convertStreamToString(url.openStream());
    }

    public static String convertStreamToString(InputStream is) throws IOException
    {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null)
        {
            StringBuilder sb = new StringBuilder();
            String line;

            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line).append("\n");
                }
            } finally
            {
                is.close();
            }
            return sb.toString();
        } else
            return "";
    }
}
